import { lazy, Suspense, useEffect, useState } from 'react'
import { Navigate, useRoutes } from 'react-router-dom'
import Loading from '@/components/Loading'
import { AuthRoute } from '@/components/AuthRoute'
import { http } from '@/utils/http'
const Login = lazy(() => import('@/pages/Login'))
const NewsSandBox = lazy(() => import('@/pages/NewsSandBox'))
const Home = lazy(() => import('@/pages/NewsSandBox/Home'))
const UserList = lazy(() => import('@/pages/NewsSandBox/User-manage/UserList'))
const RoleList = lazy(() => import('@/pages/NewsSandBox/Right-manage/RoleList'))
const RightList = lazy(() => import('@/pages/NewsSandBox/Right-manage/RightList'))
const NewsAdd = lazy(() => import('@/pages/NewsSandBox/News-manage/NewsAdd'))
const NewsDraft = lazy(() => import('@/pages/NewsSandBox/News-manage/NewsDraft'))
const NewsCategory = lazy(() => import('@/pages/NewsSandBox/News-manage/NewsCategory'))
const NewsPreview = lazy(() => import('@/pages/NewsSandBox/News-manage/NewsPreview'))
const NewsUpdate = lazy(() => import('@/pages/NewsSandBox/News-manage/NewsUpdate'))
const Audit = lazy(() => import('@/pages/NewsSandBox/Audit-manage/Audit'))
const AuditList = lazy(() => import('@/pages/NewsSandBox/Audit-manage/AuditList'))
const Unpublished = lazy(() => import('@/pages/NewsSandBox/Publish-manage/Unpublished'))
const Published = lazy(() => import('@/pages/NewsSandBox/Publish-manage/Published'))
const Sunset = lazy(() => import('@/pages/NewsSandBox/Publish-manage/Sunset'))
const News = lazy(() => import('@/pages/News/News'))
const Detail = lazy(() => import('@/pages/News/Detail'))
const NoPermission = lazy(() => import('@/components/NoPermission'))

// 从路径中映射组件
const LocalRouterMap = {
  "/home": <Home />,
  "/user-manage/list": <UserList />,
  "/right-manage/role/list": <RoleList />,
  "/right-manage/right/list": <RightList />,
  "/news-manage/add": <NewsAdd />,
  "/news-manage/draft": <NewsDraft />,
  "/news-manage/category": <NewsCategory />,
  "/news-manage/preview/:id": <NewsPreview />,
  "/news-manage/update/:id": <NewsUpdate />,
  "/audit-manage/audit": <Audit />,
  "/audit-manage/list": <AuditList />,
  "/publish-manage/unpublished": <Unpublished />,
  "/publish-manage/published": <Published />,
  "/publish-manage/sunset": <Sunset />
}

const IndexRouter = () => {
  let rights = []
  if (
    window.sessionStorage.getItem('news') &&
    window.sessionStorage.getItem('news') !== "undefined"
  ) {
    rights = JSON.parse(window.sessionStorage.getItem('news')).role?.rights
  }
  // 检查本地路由映射表 / 有无页面级路由权限
  const checkRoute = item => {
    return LocalRouterMap[item.key] && (item.pagepermisson || item.routepermisson)
  }
  // 检查当前登录用户有无权限
  const checkUserPermission = item => {
    return (
      Array.isArray(rights) ?
        rights?.includes(item.key) :
        rights?.checked.includes(item.key)
    )
  }

  // 存放服务器返回的扁平化路径数据数组
  const [BackRouteList, setBackRouteList] = useState([])

  useEffect(() => {
    Promise.all([
      http.get('/rights'),
      http.get('/children')
    ])
      .then(res => {
        setBackRouteList([
          ...res[0].data,
          ...res[1].data
        ])
        console.log([...res[0].data, ...res[1].data])
      })
  }, [])

  const element = useRoutes([
    {
      path: '/login',
      element: <Suspense fallback={<Loading />}><Login /></Suspense>
    },
    {
      path: '/',
      element: <AuthRoute>
        <Suspense fallback={<Loading />}><NewsSandBox /></Suspense>
      </AuthRoute>,
      children: [
        {
          path: '',
          element: <Navigate to='home' replace />
        },
        ...BackRouteList.map(item => {
          if (checkRoute(item) && checkUserPermission(item)) {
            return {
              path: item.key,
              element: <AuthRoute>
                <Suspense fallback={<Loading />}>
                  {LocalRouterMap[item.key]}
                </Suspense>
              </AuthRoute>
            }
          }
          return {}
        }),
        {
          // 如果没有匹配的路径，显示NoPermission 无访问权限403 路由
          path: '*',
          element: <Suspense fallback={<Loading />}><NoPermission /></Suspense>
        }
      ]
    },
    {
      path: '/news',
      element: <Suspense fallback={<Loading />}><News /></Suspense>
    },
    {
      path: '/detail/:id',
      element: <Suspense fallback={<Loading />}><Detail /></Suspense>
    }
  ])
  return element;
}
export default IndexRouter;